package com.frame.work.rabbitmq;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.frame.work.entity.UserLoginMessage;
import com.frame.work.entity.UserReqCount;
import com.frame.work.service.UserLoginMessageService;
import com.frame.work.service.UserReqCountService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author wjming
 */
@Component
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserReqCountListen {
    private final UserReqCountService reqCountService;
    private final UserLoginMessageService loginMessageService;

    /**
     * 消息处理
     */
    @RabbitListener(queues = "${topic.rabbit.userReqCount}")
    public void userReqCount(Map<String, Object> userReq, Channel rabbitChannel, @Headers Map<String, Object> headers) {
        RabbitmqEnum action = RabbitmqEnum.RETRY;
        String userId = (String) userReq.get("userId");
        String account = (String) userReq.get("account");
        String orgCode = (String) userReq.get("orgCode");
        try {
            UserReqCount userReqCount = reqCountService.getOne(Wrappers.<UserReqCount>lambdaQuery()
                    .eq(UserReqCount::getUserId, userId));
            if (userReqCount != null) {
                userReqCount.setReqCount(userReqCount.getReqCount() + 1);
                userReqCount.setAccount(account);
                userReqCount.setOrgCode(orgCode);
                this.reqCountService.updateById(userReqCount);
            } else {
                UserReqCount userReqCount1 = new UserReqCount();
                userReqCount1.setUserId(userId);
                userReqCount1.setReqCount(1L);
                userReqCount1.setAccount(account);
                userReqCount1.setOrgCode(orgCode);
                this.reqCountService.save(userReqCount1);
            }

            action = RabbitmqEnum.ACCEPT;
        } catch (Exception e) {
            action = RabbitmqEnum.REJECT;
        } finally {
            try {
                //通过finally块来保证ACK/NACK会执行一次
                if (action.equals(RabbitmqEnum.ACCEPT)) {
                    rabbitChannel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG), true);
                } else if (action.equals(RabbitmqEnum.RETRY)) {
                    rabbitChannel.basicNack((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false, true);
                } else {
                    rabbitChannel.basicNack((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false, false);
                }
            } catch (Exception e) {
            }
        }
    }


    /**
     * 消息处理
     */
    @RabbitListener(queues = "${topic.rabbit.userLoginMessage}")
    public void userLoginMessage(Map<String, Object> userReq, Channel rabbitChannel, @Headers Map<String, Object> headers) {
        RabbitmqEnum action = RabbitmqEnum.RETRY;
        String id = (String) userReq.get("id");
        String account = (String) userReq.get("account");
        String orgCode = (String) userReq.get("orgCode");
        String sourceId = (String) userReq.get("sourceId");
        Integer sourceType = (Integer) userReq.get("sourceType");
        LocalDateTime time = (LocalDateTime) userReq.get("time");

        try {
            UserLoginMessage userLoginMessage = new UserLoginMessage();
            userLoginMessage.setUserId(id);
            userLoginMessage.setAccount(account);
            userLoginMessage.setOrgCode(orgCode);
            userLoginMessage.setSourceId(sourceId);
            userLoginMessage.setSourceType(sourceType);
            userLoginMessage.setLoginTime(time);
            loginMessageService.save(userLoginMessage);

            action = RabbitmqEnum.ACCEPT;
        } catch (Exception e) {
            action = RabbitmqEnum.REJECT;
        } finally {
            try {
                //通过finally块来保证ACK/NACK会执行一次
                if (action.equals(RabbitmqEnum.ACCEPT)) {
                    rabbitChannel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG), true);
                } else if (action.equals(RabbitmqEnum.RETRY)) {
                    rabbitChannel.basicNack((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false, true);
                } else {
                    rabbitChannel.basicNack((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false, false);
                }
            } catch (Exception e) {
            }
        }
    }
}
